<template>
    <view>
        <!-- 自定义导航栏 -->
        <myNavigation ref="navBar"></myNavigation>
        <view class="cover"></view>
        <view class="container">
            <view class="content">

                <!-- 登录 -->
                <view class="form-container form_login" :class="{hide: !isLogin}">
                    <view class="title_photo  iconfont">&#xe601;</view>
                    <!-- 账号 -->
                    <view class="login_name_box input-field">
                        <input class="login_name iconfont" type="number" placeholder="请输入手机号" @input="validateLoginName"
                            v-model="loginName" />
                        <view class="input_tip iconfont" v-if="loginName!==''" :class="{error: !isValidLoginName}">
                            {{!isValidLoginName ?"请输入正确的手机号":"&#xe619;"}}
                        </view>
                    </view>
                    <!-- 密码 -->
                    <view class="password_box input-field">
                        <input class=" password iconfont" :type="passwordInput[isShowPassword]" placeholder="请输入密码"
                            v-model="password" @input="validatePassword" />
                        <view class="input_tip iconfont" v-if="password !== ''" :class="{error: !isValidPassword}">
                            {{!isValidPassword? "密码格式错误(8~18位&nbsp;字母或数字&nbsp; _+ - / * )":"&#xe619;"}}
                        </view>
                        <view class="password_show iconfont" @tap.stop="togglePasswordVisibility"
                            v-if="password !== '' ">{{isShowPassword ===0 ? "&#xeb45;":"&#xeb46;"}}</view>
                    </view>
                    <view class="confirm_rule">
                        <view class="icon iconfont" @tap="handleRule" :class="{success:isAgreeRule}">
                            {{isAgreeRule?"&#xe619;":"&#xe62d;"}}
                        </view>
                        <view class="rule">我已阅读并同意炒个菜吧的<text>《用户协议》</text>和<text>《隐私协议》</text></view>
                    </view>

                    <button class="login-button" type="primary" @tap="handleLogin">登&emsp;录</button>
                    <view class="toggle">
                        <button class="toggle-btn" @tap="toggleRegister">立即注册</button>
                        <button class="toggle-btn" @tap="togglePassword">找回密码</button>
                    </view>
                </view>

                <!-- 注册 -->
                <view class="form-container form_register" :class="{hide: !(!isLogin  && !isForgetPassword)}">
                    <view class="title">注&emsp;册</view>

                    <!-- 账号 -->
                    <view class=" login_name_box  input-field">
                        <input class="login_name iconfont" type="number" placeholder="请输入手机号" v-model="loginName"
                            @input="validateLoginName" />
                        <view class="input_tip iconfont" v-if="loginName!==''" :class="{error: !isValidLoginName}">
                            {{!isValidLoginName ?"请输入正确的手机号":"&#xe619;"}}
                        </view>
                    </view>

                    <!-- 密码 -->
                    <view class="password_box input-field">
                        <input class=" password iconfont" :type="passwordInput[isShowPassword]" placeholder="请输入密码"
                            v-model="password" @input="validatePassword" />
                        <view class="input_tip iconfont" v-if="password !== ''" :class="{error: !isValidPassword}">
                            {{!isValidPassword? "密码格式错误(8~18位&nbsp;字母或数字&nbsp; _+ - / * )":"&#xe619;"}}
                        </view>
                        <view class="password_show iconfont" @tap.stop="togglePasswordVisibility"
                            v-if="password !== '' ">{{isShowPassword===0? "&#xeb45;":"&#xeb46;"}}
                        </view>

                    </view>

                    <!-- 二次输入密码 -->
                    <view class="password_box input-field">
                        <input class=" password iconfont" :type="rePasswordInput[isShowRePassword]"
                            placeholder="请再次输入密码" v-model="confirmPassword" @input="validateRePassword" />

                        <view v-if="confirmPassword!== ''" :class="{ error: password !==confirmPassword}"
                            class="input_tip iconfont">
                            {{password !== confirmPassword ?'两次输入的密码不一致':'&#xe619;'}}
                        </view>
                        <view class="password_show iconfont" @tap.stop="toggleRePasswordVisibility"
                            v-if="confirmPassword !== '' ">{{isShowRePassword===0? "&#xeb45;":"&#xeb46;"}}
                        </view>

                    </view>

                    <view class="code-container  input-field">
                        <input type="number" maxlength="6" class="iconfont code" placeholder="请输入验证码"
                            @input="inputCode" />
                        <view class="code_btn" :disabled="countdown > 0" @tap="sendCode">{{ countdown > 0 ?
                            `${countdown}s后重试` :
                            '获取验证码' }}</view>
                    </view>
                    <button class="register-button" type="primary" @tap="handleRegister">注&emsp;册</button>
                    <view class="toggle">
                        <button class="toggle-btn" @tap="toggleLogin">返回登录</button>
                        <button class="toggle-btn" @tap="togglePassword">找回密码</button>
                    </view>
                </view>

                <!-- 找回密码 -->
                <view class="form-container from_reset_password" :class="{hide: !isForgetPassword}">
                    <view class="title">找回密码</view>

                    <!-- 账号 -->
                    <view class=" login_name_box  input-field">
                        <input class="login_name iconfont" type="number" placeholder="请输入找回账号的手机号" v-model="loginName"
                            @input="validateLoginName" />
                        <view class="input_tip iconfont" v-if="loginName!==''" :class="{error: !isValidLoginName}">
                            {{!isValidLoginName ?"请输入正确的手机号":"&#xe619;"}}
                        </view>
                    </view>

                    <button class="confirm_code" @tap="confirmLoginName">点我验证</button>
                    <view v-if="isConfirmCode" class="confirm_code_tip" :class="confirmCodeTip.messageClass">{{
                        confirmCodeTip.message }}</view>


                    <!-- 重置密码 -->
                    <view class="reset_password_box" :class="{hide : !isExistLoginName}">
                        <view class="code-container  input-field">
                            <input type="number" maxlength="6" class="iconfont code" placeholder="请输入验证码"
                                @input="inputCode" />
                            <view class="code_btn" :disabled="countdown > 0" @tap="sendCode">{{ countdown > 0 ?
                                `${countdown}s后重试` :
                                '获取验证码' }}</view>
                        </view>

                        <!-- 密码 -->
                        <view class="password_box input-field">
                            <input class=" password iconfont" :type="passwordInput[isShowPassword]" placeholder="请输入新密码"
                                v-model="password" @input="validatePassword" />
                            <view class="input_tip iconfont" v-if="password !== ''" :class="{error: !isValidPassword}">
                                {{!isValidPassword? "密码格式错误(8~18位&nbsp;字母或数字&nbsp; _+ - / * )":"&#xe619;"}}
                            </view>
                            <view class="password_show iconfont" @tap.stop="togglePasswordVisibility"
                                v-if="password !== '' ">{{isShowPassword===0? "&#xeb45;":"&#xeb46;"}}</view>

                        </view>

                        <!-- 二次输入密码 -->
                        <view class="password_box input-field">
                            <input class=" password iconfont" :type="rePasswordInput[isShowRePassword]"
                                placeholder="请再次输入密码" v-model="confirmPassword" @input="validateRePassword" />
                            <view class="password_show iconfont" @tap.stop="toggleRePasswordVisibility"
                                v-if="confirmPassword !== '' ">{{isShowRePassword===0? "&#xeb45;":"&#xeb46;"}}</view>

                            <view v-if="confirmPassword!== ''" :class="{ error: password !==confirmPassword}"
                                class="input_tip iconfont">
                                {{password !== confirmPassword ?'两次输入的密码不一致':'&#xe619;'}}
                            </view>
                        </view>

                        <button class="getPassword_button" type="primary" @tap="modifyPassword">确&nbsp;认&nbsp;修&nbsp;改
                        </button>


                    </view>
                    <view class="toggle">
                        <button class="toggle-btn" @tap="toggleLogin">返回登录</button>
                        <button class="toggle-btn" @tap="toggleRegister">没有账号立即注册</button>
                    </view>
                </view>

            </view>
        </view>

    </view>
</template>

<script setup>
    import { ref, onMounted, inject, reactive } from 'vue';
    import "./login.scss";
    import Taro, { useRouter } from "@tarojs/taro";
    import { AtInput, AtButton } from 'taro-ui-vue3'
    import myNavigation from "../../../components/myNavigation.vue";
    // 注入配置
    const config = inject('config');
    const baseUrl = config.baseUrl; // 从全局配置中读取 baseUrl


    // 导航栏信息
    const navBar = ref(null);
    const navigationHome = () => {
        Taro.switchTab({
            url: '../../../pages/index/index',
        });
    };
    const setNavBar = () => {
        if (navBar.value) {
            navBar.value.navigationHome = navigationHome;
            navBar.value.navigationTitle = `用户登录`;
        }
    }

    const isLogin = ref(true)
    const isValidLoginName = ref(true);
    const isValidPassword = ref(true);
    const isValidRePassword = ref(true);
    const isAgreeRule = ref(false);
    const isForgetPassword = ref(false);
    const isExistLoginName = ref(false);
    const isConfirmCode = ref(false);

    // 0为隐藏,1为显示
    const isShowPassword = ref(0);
    const isShowRePassword = ref(0);

    const loginName = ref('')
    const password = ref('')
    const confirmPassword = ref('')
    const verificationCode = ref('')
    const code = ref('');
    const countdown = ref(0);

    const passwordInput = ["password", "text"];
    const rePasswordInput = ["password", "text"];


    const confirmCodeTip = reactive({
        message: "",
        messageClass: "",
    })

    const loginNameRegex = /^1[3-9]\d{9}$/
    const passwordRegex = /^[\w\_\+\-\*\/]{8,18}$/;


    const userAccount = reactive({
        loginName: "",
        password: "",
    })

    // 用户登录
    const handleLogin = () => {
        if (!validateInput()) return
        // 处理登录逻辑
        userAccount.loginName = loginName.value;
        userAccount.password = password.value;
        console.log(userAccount);
        Taro.request({
            url: `${baseUrl}/user/login`,
            method: 'POST',
            data: userAccount,
            success: function (res) {
                if (typeof (res.data.data) === 'number') {
                    Taro.setStorageSync("userId", res.data.data);
                    successToIndex("登录成功");
                }
                else {
                    showError(res.data.data);
                }
            }
        })
    }

    // 注册用户
    const handleRegister = () => {
        if (!validateInput()) return
        // 处理注册逻辑
        userAccount.loginName = loginName.value;
        userAccount.password = password.value;
        Taro.request({
            url: `${baseUrl}/user/register`,
            method: 'POST',
            data: userAccount,
            success: function (res) {
                if (res.data.message === "success") {
                    successToLogin(res.data.data);
                } else {
                    showError(res.data.data)
                }
            }
        });
    }



    // 修改密码
    const modifyPassword = () => {
        if (!validateInput()) return;

        userAccount.loginName = loginName.value;
        userAccount.password = password.value;
        // 具体的修改密码请求:
        Taro.request({
            url: `${baseUrl}/user/modifyUser`,
            method: 'PUT',
            data: userAccount,
            success: function (res) {
                if (res.data.message === "success") {
                    successToLogin(res.data.data);
                } else {
                    showError(res.data.data)
                }
            }
        });
    };

    // 找回密码验证
    const confirmLoginName = () => {
        // 验证账号是否存在


        Taro.request({
            url: `${baseUrl}/user/userIsExist?loginName=${loginName.value}`,
            success: function (res) {
                isConfirmCode.value = true;
                console.log(res.data.data);
                if (res.data.message === "success") {
                    isExistLoginName.value = true;

                } else {
                    isExistLoginName.value = false;
                }

                if (isExistLoginName.value) {
                    confirmCodeTip.message = "验证成功";
                    confirmCodeTip.messageClass = "success_tip";
                } else {
                    confirmCodeTip.message = res.data.data;
                    confirmCodeTip.messageClass = "error_tip";
                }
            }
        });


    }

    // 是否显示密码
    const togglePasswordVisibility = () => {
        if (isShowPassword.value === 0) isShowPassword.value = 1;
        else isShowPassword.value = 0;
    }

    //  是否显示二次输入密码
    const toggleRePasswordVisibility = () => {
        if (isShowRePassword.value === 0) isShowRePassword.value = 1;
        else isShowRePassword.value = 0;
    }


    // 函数:成功后跳转登录页面
    function successToLogin(msg) {
        const curTime = ref(3);
        Taro.showToast({
            title: `${msg}`,
            icon: 'success',
            mask: true,
            duration: 1000, // 持续时间为2秒
            complete: () => {
                const intervalId = setInterval(() => {
                    curTime.value -= 1;
                    if (curTime.value > 0) {
                        Taro.showToast({
                            title: `${msg},${curTime.value}s后跳转到登录页面`,
                            icon: 'none',
                            mask: true,
                            duration: 1000 // 每次显示1秒
                        });
                    } else {
                        clearInterval(intervalId); // 清除定时器
                        toggleLogin(); // 执行跳转操作
                    }
                }, 1000);
            }
        });
    }

    // 函数：登录成功后跳转上一页：
    function successToIndex(msg) {
        const curTime = ref(2);
        Taro.showToast({
            title: `${msg}`,
            icon: 'success',
            mask: true,
            duration: 1000, // 持续时间为2秒
            complete: () => {
                const intervalId = setInterval(() => {
                    curTime.value -= 1;
                    if (curTime.value > 0) {
                        Taro.showToast({
                            title: `${msg},${curTime.value}s后返回上一页`,
                            icon: 'none',
                            mask: true,
                            duration: 1000 // 每次显示1秒
                        });
                    } else {
                        clearInterval(intervalId); // 清除定时器
                        // 执行跳转操作
                        Taro.navigateBack({
                            delta: 1
                        });
                    }
                }, 1000);
            }
        });
    }
    // 函数:失败显示
    function showError(msg) {
        Taro.showToast({
            title: `${msg}`,
            icon: 'error',
            duration: 2000, // 持续时间为2s
        });
    }


    // 同意协议
    const handleRule = () => {
        isAgreeRule.value = !isAgreeRule.value;
    }

    // 判断账号输入格式是否正确
    const validateLoginName = (e) => {
        loginName.value = e.detail.value;
        if (!loginNameRegex.test(loginName.value)) {
            isValidLoginName.value = false
        } else isValidLoginName.value = true
        return e.detail.value
    }

    // 判断密码输入格式是否正确
    const validatePassword = (e) => {
        password.value = e.detail.value;
        if (!passwordRegex.test(password.value)) {
            isValidPassword.value = false;
        } else isValidPassword.value = true;
        return e.detail.value
    }

    // 判断二次输入密码输入格式是否正确
    const validateRePassword = (e) => {
        confirmPassword.value = e.detail.value;
        if (!passwordRegex.test(confirmPassword.value)) {
            isValidRePassword.value = false;
        } else isValidRePassword.value = true;
        return e.detail.value
    }

    // 输入验证码
    const inputCode = (e) => {
        code.value = e.detail.value;

    }



    const validateInput = () => {
        if (!loginNameRegex.test(loginName.value)) {
            Taro.showToast({ title: '手机号格式不正确', icon: 'none' })
            return false
        }
        if (!passwordRegex.test(password.value)) {
            Taro.showToast({ title: '密码格式不正确', icon: 'none' })
            return false
        }
        if (!isLogin.value && password.value !== confirmPassword.value) {
            Taro.showToast({ title: '两次输入的密码不一致', icon: 'none' })
            return false
        }
        if (!isLogin.value && password.value !== confirmPassword.value) {
            Taro.showToast({ title: '两次输入的密码不一致', icon: 'none' })
            return false
        }
        if (!isLogin.value && !(code.value === "123456")) {
            Taro.showToast({ title: '验证码错误,请重新检查', icon: 'none' })
            return false
        }
        if (isForgetPassword.value && !(code.value === "123456")) {
            Taro.showToast({ title: '验证码错误,请重新检查', icon: 'none' })
            return false
        }
        if (!isAgreeRule.value && isLogin.value) {
            Taro.showToast({ title: '登录前请先阅读并且同意相关协议', icon: 'none' })
            return false
        }

        return true
    }

    // 注册显示
    const toggleRegister = () => {
        isLogin.value = false;
        isForgetPassword.value = false;
        isShowPassword.value = 0
        isShowRePassword.value = 0
    }
    // 找回密码显示
    const togglePassword = () => {
        isShowPassword.value = 0
        isShowRePassword.value = 0
        isConfirmCode.value = false;
        isForgetPassword.value = true;
        isExistLoginName.value = false;
        isLogin.value = false;

    }
    // 返回登录
    const toggleLogin = () => {
        isShowPassword.value = 0
        isLogin.value = true;
        isForgetPassword.value = false
    }
    //发送验证码
    const sendCode = () => {
        if (countdown.value === 0) {
            // 发送验证码逻辑
            countdown.value = 60;
            const interval = setInterval(() => {
                countdown.value--;
                if (countdown.value === 0) clearInterval(interval);
            }, 1000);
        }
    };

    onMounted(() => {
        setNavBar();
    });
</script>

<style lang="scss" scoped></style>